import 'package:casdon/modules/recipe/data/api/recipe_user_info_api.dart';
import 'package:casdon/modules/recipe/domain/usecase/recipe_del_favorite_usecase.dart';
import 'package:casdon/modules/recipe/domain/usecase/recipe_put_favorite_usecase.dart';
import 'package:casdon/modules/recipe/domain/usecase/recipe_user_info_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class RecipeFavoriteOperateNotifier extends StateNotifier<bool> {
  final Ref ref;
  final String recipeId;
  late final ProviderSubscription<AsyncValue<RecipeUserInfoApi?>> _userInfoSub;

  RecipeFavoriteOperateNotifier(this.ref, this.recipeId)
      : super(
          ref.read(recipeUserInfoProvider(recipeId)).maybeWhen(
                data: (info) => info?.isCollect ?? false,
                orElse: () => false,
              ),
        ) {
    _userInfoSub = ref.listen<AsyncValue<RecipeUserInfoApi?>>(
      recipeUserInfoProvider(recipeId),
      (previous, next) {
        next.whenOrNull(
          data: (info) => state = info?.isCollect ?? false,
        );
      },
    );
    ref.onDispose(_userInfoSub.close);
  }

  Future<bool> addFavorite(String recipeId) async {
    final ret = await ref
        .read(recipePutFavoriteUsecaseProvider)
        .execute(menuId: recipeId);
    if (ret == true) {
      state = true;
    }
    return ret;
  }

  Future<bool> delFavorite(String recipeId) async {
    final ret = await ref
        .read(recipeDelFavoriteUsecaseProvider)
        .execute(menuId: recipeId);
    if (ret == true) {
      state = false;
    }
    return ret;
  }
}

final recipeFavoriteOperateProvider = StateNotifierProvider.autoDispose
    .family<RecipeFavoriteOperateNotifier, bool, String>((ref, recipeId) {
      return RecipeFavoriteOperateNotifier(ref, recipeId);
    });
